<template>
<div class="container">
    <div class= " row" >
        <button class="btn btn-lg btn-primary" @click.stop.prevent="ConnectMqttServer( '111.231.108.101' , 9000 )"> 链接mqtt服务器</button>
        <div class="container" >
            <button class="btn btn-lg btn-primary" @click.stop.prevent="PublishToXiaoZhang( 'a' )"> 测试bufang</button>
            <button class="btn btn-lg btn-primary" @click.stop.prevent="PublishToXiaoZhang( 'b' )"> 测试chefang</button>
            <button class="btn btn-lg btn-primary" @click.stop.prevent="PublishToXiaoZhang( 'c' )"> 测试panglu</button>
        </div>
    </div>

    <form class="form-horizontal ">
        <div class="form-group row">
            <label  class="col-sm-2 control-label" >
            ip: 
            </label>
            <div class="col-sm-4">
                <input class="form-control" type="text" v-model="ip"></input>
            </div>
        </div>

        <div class="form-group row">
            <label class=" col-sm-2 control-label ">
            mac: 
            </label>
            <div class="col-sm-4" >
                <input class="form-control" type="text" v-model="mac"></input>
            </div>
        </div>

        <div class="form-group row">
            <div class="col-sm-2 col-sm-offset-2 text-center">
                <button class="btn btn-lg btn-primary" @click.prevent.stop="addDevice"> 安装新设备</button>
            </div>
        </div>
    </form>

    <table class="table table-default">
        <thead>
            <tr>
                <td>
                    设备MAC
                </td>
                <td>
                    设备IP
                </td>
                <td>
                   subKey 
                </td>
                <td>
                   subChannel 
                </td>
                <td>
                   pubKey 
                </td>
                <td>
                    pubChannel
                </td>
                <td>
                    选择防区号
                </td>
                <td>
                    操作
                </td>
            </tr>
        </thead>
        <tbody>
            <tr v-for="protector in protectors " >
                <td class="">
                    {{protector.mac}}
                </td>
        
                <td class="">
                    {{protector.ip}}
                </td>

                <td class="">
                    {{protector.subKey}}
                </td>

                <td class="">
                    {{protector.subChannel}}
                </td>
    
                <td class="">
                    {{protector.pubKey}}
                </td>
    
                <td class="">
                    {{protector.pubChannel}}
                </td>

                <td>
                    <input v-model="protector.current_arm_area" ></input>
                </td>
                <td>
                    {{ protector.arm_areas }}
                </td>
    
                <td class="">
                    <button class="btn btn-lg btn-primary" @click.stop.prevent="AlarmByMqtt( protector, 'chefang')"> http报警</button>
                    <button class="btn btn-lg btn-primary" @click.stop.prevent="PublishState( protector, 'chefang')"> 模拟键盘撤防</button>
                    <button class="btn btn-lg btn-primary" @click.stop.prevent="PublishState( protector, 'bufang')"> 模拟键盘布防</button>
                    <button class="btn btn-lg btn-primary" @click.stop.prevent="PublishState( protector, 'panglu')"> 模拟键盘旁路</button>
                    <button class="btn btn-lg btn-primary" @click.stop.prevent="PublishState( protector, 'alarm')"> 模拟主机报警</button>
                </td>
            </tr>
        </tbody>
    </table>
</div>
</template>
<script>
import Mqtt from 'mqtt'
import axios from 'axios'
export default { 
    name: 'test_device',
    data(){ 
        return { 
            ip: "10.0.1." + Math.floor(Math.random( )* 100),
            mac: "12345678" + Math.floor( Math.random() * 10000 ),
            protectors: [],
            //fake promise
            mclient:null
        }
    },

    methods: {
        addDevice( e_) { 
            var vm = this
            var mac = this.mac
            var ip = this.ip
            var pendingDevice = {mac, ip }

            this.ip = "10.0.1." + Math.floor(Math.random( )* 200),
            this.mac = "12345678" + Math.floor( Math.random() * 10000 ),

            axios.put( '/api/v1/security/protectors', { mac: mac, ip: ip } )
            .then( ( resp ) => { 
                var data = resp.data
                console.log( data );

                pendingDevice.subKey = data.subscribeKey 
                pendingDevice.subChannel = data.subscribeChannel 
                pendingDevice.mclient = Mqtt.connect( { host: data.host, port: data.port } )
                pendingDevice.mclient.on( 'connect', ( ack )=>{
                    console.log( pendingDevice.mac, " connected")
                    this.protectors.push( pendingDevice )
                })
                pendingDevice.mclient.subscribe( pendingDevice.subChannel )
                pendingDevice.mclient.on( 'message', (msg)=>{
                    console.log( msg )
                    if( msg.type == 'init'){
                        pendingDevice.pubKey = msg.publishKey;
                        pendingDevice.pubChannel = msg.publishChannel;
                        this.$set( this.protectors, this.protectors.length - 1, pendingDevice )
                    }
                })
                pendingDevie.mclient.on( "error", ( msg ) => { 
                    console.error(  msg )
                })
            })
            .catch( function( resp ) { 
                console.log( resp );
            })
        },

        AlarmByMqtt( protector ) { 
            axios.post( '/api/v1/security/protectors/Alarm', { mac: protector.mac, ip: protector.ip, arm_area_idx: this.current_arm_area } )
            .then( function( resp ) { 
                console.log( resp.data );
            })
            .catch( function( error ) { 
                console.log( error )
            })
        },

        PublishState( protector, s  ){
            console.log( 'current protector: ', protector )
            protector.mclient.publish( protector.pubChannel + "/status/" , JSON.stringify( { status:s,  arm_area_idx: protector.current_arm_area } ) )
        },
        PublishToXiaoZhang(  op ){
            this.mclient.publish( { key:"VGT3sn4nNo22XwjEZJSsmgeNvsTBX_g3",  channel: "device/xiaozhang/test" , message: op + "+9"  } )
        },

        refreshState(){
            var vm = this
            return axios.get( "/api/v1/security/protectors").then( function( resp ){
                var protectors = resp.data.protectors
                for( let i = 0; i < protectors.length; i++ ){
                    protectors[i].current_arm_area = 0
                }
                vm.protectors = protectors;
            })
        },

        handleMqttMsg( protector, msg ){
            if( msg.channel.match( /init\/$/) ) { 
                console.log( msg.asObject() )
            }
            else if( msg.channel.match( /control\/$/) ) {
                console.log( msg.asObject() )
            }
            console.log( "handle mqtt msg for ", protector.mac )
            console.log( msg )
            console.log( '----------------------')
            msg = msg.asObject()
            if( msg.type == 'init') {
                protector.pubKey = msg.publishKey
                protector.pubChannel = msg.publishChannel
            }
            else { 
                if( msg.op  == "chefang" ) { 
                    console.log( "chefang")
                    protector.arm_areas[msg.idx] = "c"
                }
                else if( msg.op == "bufang"){
                    console.log( "bufang")
                    protector.arm_areas[msg.idx] = "b"
                }
                else if( msg.op == "panglu") {
                    console.log( "panglu")
                    protector.arm_areas[msg.idx] = "p"
                }
                else{
                    console.log( "unexpected control message ")
                    return
                }
                var data = JSON.stringify( { s: protector.arm_areas[msg.idx], idx: msg.idx })
                protector.mclient.publish( { key: protector.pubKey, channel: protector.pubChannel, data } )
            }
        },

        ConnectMqttServer( host, port ){
            this.mclient = Mqtt.connect({host: host, port: port  } )
            this.mclient.on( 'connect', ( msg ) => { console.log( msg ); console.log( "connected ... "); } )
            this.mclient.on( 'error', (error)=>{
                console.log( "--------> get error message ", error )
            })
        }
    },
    async created(){
        var vm = this;
        await this.refreshState();

        var promiseAll = []
        var promiseAllConnect = []

        function promisePub ( idx ) { 
            var protector = vm.protectors[idx]
            return new Promise( function( resolve, reject ){ 
                axios.post( '/api/v1/security/protectors/addtest', { mac: protector.mac, ip: protector.ip} ).then( function( resp ) { 
                    var data = resp.data
                    protector.host = data.host
                    protector.port = data.port
                    protector.subKey = data.subscribeKey
                    protector.subChannel = data.subscribeChannel
                    protector.pubKey = data.publishKey
                    protector.pubChannel = data.publishChannel
                    protector.mclient = Mqtt.connect( { host: data.host, port: data.port } ) 
                    protector.mclient.on( 'connect', function( msg ){ 
                        console.log( protector.mac , " connected ! ")
                        protector.mclient.subscribe( protector.subChannel + "/control/")
                        protector.mclient.subscribe( protector.subChannel + "/init/" )
                    })

                    protector.mclient.on( 'message', function( msg ){
                        msg = msg.asObject()
                        vm.handleMqttMsg( protector, msg )
                        vm.$set( vm.protectors,  idx, protector )
                        if( msg.type == "init"){
                            resolve( protector )
                        }
                        else { 

                        }
                    })
                    protector.mclient.on( 'error', function( msg ){ 
                        console.error( msg )
                    })
                });
            })
        }

        for( let i = 0; i < this.protectors.length; i++ ) {
            promiseAllConnect.push( promisePub( i ) )
        }
        return Promise.all( promiseAllConnect ).then(function( protectors ){ vm.protectors = protectors;  }) ;
    }
}

</script>
<style>
.form-group label{
    margin-right: -200px;
}
.form-group input {
    margin-left:200px;
}
</style>
